package com.ocom.mqsimple.business.bigfile.impl;


import com.alibaba.fastjson.JSON;
import com.ocom.common.request.simple.BigFileRequest;
import com.ocom.common.utils.StringUtil;
import com.ocom.mqsimple.business.bigfile.BigFileProductService;
import com.ocom.mqsimple.utils.BigFileRabbitProductUitl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;


@Service
public class BigFileProductServiceImpl implements BigFileProductService {
	private final Logger log = LoggerFactory.getLogger(BigFileProductServiceImpl.class);

	@Autowired
	private BigFileRabbitProductUitl bigFileRabbitProductUitl;


//	@Resource
//	RedisUtil redisUtil;

	/**
	 * 处理人员图片
	 */
	public void handle(BigFileRequest request) {

		log.info("发送大文件mq-开始【{}】",request);
		//消息队列调用减库存接口  优先级越高越先执行完

//		redisUtil.set(request.getUrl(),request.getComplateUrl(), 120l);
		request.setComplateUrl("");

        String msg = JSON.toJSONString(request);
        bigFileRabbitProductUitl.bigFileSend(msg,15);

        log.info("发送大文件mq-完成【{}】",msg);

	}


	public String download(Map<String ,Object> map){

		List<String> urls = (List<String>) map.get("urls");
		String fileName = (String) map.get("fileName");
		String savePath = "images";
		for (String imgUrl : urls) {
			if (StringUtil.isEmpty(imgUrl)){
				continue;
			}
			log.info("imgUrl{{}}",imgUrl);
			try {
				fileName = imgUrl.substring(imgUrl.lastIndexOf("/"));
				log.info("savePath{{}}", savePath);
				// 构造URL
				URL url = new URL(imgUrl);
				// 打开连接
				URLConnection con = url.openConnection();
				con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
				//设置请求超时为5s
				con.setConnectTimeout(5*1000);
				// 输入流
				InputStream is = con.getInputStream();
				// 1K的数据缓冲
				byte[] bs = new byte[1024];
				// 读取到的数据长度
				int len;
				// 输出的文件流
				File sf=new File(String.valueOf(savePath));
				if(!sf.exists()){
					sf.mkdirs();
				}
				OutputStream os = new FileOutputStream(sf.getPath()+"/"+fileName);
				// 开始读取
				while ((len = is.read(bs)) != -1) {
					os.write(bs, 0, len);
				}
				// 完毕，关闭所有链接
				os.close();
				is.close();

			}catch (Exception e){
				log.error("异常{{}}",e.getMessage());
			}
		}
		log.info("fileName{{}}",fileName);
		log.info("===================end====================");
		return savePath +fileName;
	}

}
